﻿using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using IFDB.Models.Contexts;
using IFDB.Models.Foundation;
using IFDB.ResourceLibrary;

namespace IFDB.Models.Tables
{
    public class LookupTeam : BaseTable<LookupTeam>
    {
        [Key]
        public Guid LookupTeamId { get; set; }
        public Site Site { get; set; }

        [StringLength(25)]
        public string LookupId { get; set; }
        public Guid TeamId { get; set; }

        [ForeignKey("TeamId")]
        public virtual Team Team { get; set; }

        public static LookupTeam CreateNew(Site site, string lookupId, Guid teamId)
        {
            return new LookupTeam()
            {
                LookupTeamId = Guid.NewGuid(),
                Site = site,
                LookupId = lookupId,
                TeamId = teamId
            };
        }

        public static LookupTeam Update(LookupTeam lookupTeam, Site site, string lookupId, Guid teamId)
        {
            lookupTeam.Site = site;
            lookupTeam.LookupId = lookupId;
            lookupTeam.TeamId = teamId;

            return lookupTeam;
        }

        public static LookupTeam Search(IFDBContext db, Site site, string lookupId)
        {
            var localQuery = from lookupTeam in db.LookupTeams.Local
                             where lookupTeam.Site == site
                             && lookupTeam.LookupId == lookupId
                             select lookupTeam;
            
            var query = from lookupTeam in db.LookupTeams
                        where lookupTeam.Site == site
                        && lookupTeam.LookupId == lookupId
                        select lookupTeam;

            var search = ProcessSearch(localQuery, query, false);
            return search != null ? search.Single() : null;
        }
    }
}
